package com.example.nutritionmanager.viewModels

import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.State
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.nutritionmanager.api.UserService
import com.example.nutritionmanager.bodys.requestBodys.LoginRequest
import com.example.nutritionmanager.bodys.responseBodys.LoginResponse
import com.example.nutritionmanager.data.TokenDataStore
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.HttpException
import java.io.IOException
import javax.inject.Inject

sealed class LoginState {
    object Idle : LoginState()
    object Loading : LoginState()
    data class Success(val response: LoginResponse) : LoginState()
    data class Error(val error: String) : LoginState()
}

@HiltViewModel
class LoginViewModel @Inject constructor(
    private val userService: UserService,
    private val tokenDataStore: TokenDataStore
) : ViewModel() {

    private val TAG = "LoginViewModel"

    // 内部可变状态
    private val _loginState = mutableStateOf<LoginState>(LoginState.Idle)
    // 外部只读状态
    val loginState: State<LoginState> get() = _loginState

    // 执行登录操作
    fun login(username: String, password: String) {
        Log.d(TAG, "开始登录操作，用户名: $username")
        // 更新状态为 Loading
        _loginState.value = LoginState.Loading

        // 使用协程在后台线程执行网络请求
        viewModelScope.launch {
            try {
                // 切换到 IO 线程进行网络请求
                val loginRequest = LoginRequest(username, password)
                Log.d(TAG, "发送登录请求: $loginRequest")
                val response = withContext(Dispatchers.IO) {
                    userService.login(loginRequest)
                }

                Log.d(TAG, "登录响应码: ${response.code()}, 消息: ${response.message()}")

                // 检查响应是否成功
                if (response.isSuccessful) {
                    val responseBody = response.body()
                    Log.d(TAG, "登录成功，响应体: $responseBody")
                    if (responseBody != null) {
                        // 保存 Token
                        tokenDataStore.saveToken(responseBody.token)
                        Log.d(TAG, "保存 Token 成功: ${responseBody.token}")
                        // 更新状态为 Success
                        _loginState.value = LoginState.Success(responseBody)
                        Log.d(TAG, "登录状态更新为 Success")
                    } else {
                        // 更新状态为 Error，包含错误信息
                        _loginState.value = LoginState.Error("空响应体")
                        Log.d(TAG, "登录失败，空响应体")
                    }
                } else {
                    // 更新状态为 Error，包含错误信息
                    _loginState.value = LoginState.Error("登录失败: ${response.message()}")
                    Log.d(TAG, "登录失败，响应消息: ${response.message()}")
                }
            } catch (e: IOException) {
                // 网络错误
                _loginState.value = LoginState.Error("网络错误: ${e.localizedMessage}")
                Log.e(TAG, "网络错误: ${e.localizedMessage}", e)
            } catch (e: HttpException) {
                // HTTP 错误
                _loginState.value = LoginState.Error("服务器错误: ${e.localizedMessage}")
                Log.e(TAG, "服务器错误: ${e.localizedMessage}", e)
            } catch (e: Exception) {
                // 其他未知错误
                _loginState.value = LoginState.Error("未知错误: ${e.localizedMessage}")
                Log.e(TAG, "未知错误: ${e.localizedMessage}", e)
            }
        }
    }

    // 重置登录状态为 Idle（用于错误提示后）
    fun resetState() {
        _loginState.value = LoginState.Idle
        Log.d(TAG, "登录状态重置为 Idle")
    }
}

